// pages/groupdetail/groupdetail.js
var app = getApp()
var range1, range2;
var goodstimer
var shihan = require('../../../common/fetch');
var config = require('../../../common/config');
var winScale = 750 / app.data.deviceInfo.windowWidth
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canvasflag: true,
    showLoading: true,
    shareteamid: 39,
    filterConflag: false,
    hideimg: false,
    refresh: true,
    painting: {},
    shareImage: '',
    defaults: 'https://img-oss.shihanbainian.com/shihan2/index/defaults.png'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      orderno: options.orderno
    })
    wx.hideShareMenu()
    range1 = 1090 / winScale;
    var animation1 = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation1 = animation1;

    range2 = this.data.winHeight;
    var animation2 = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation2 = animation2;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.refresh) {
      this.groupdetail(this.data.orderno)
    }
  },
  // 拼团详情
  groupdetail: function(orderno) { //get_group_buy_detail
    var that = this
    shihan.sendRequest(config.get_group_buy_detail, 'POST', {
        order_no: orderno
      })
      .then(function(response) { //sh_team_status	拼团状态(0待成团1已成团2拼团失败)
        if (response.data.code == 0) {
          // console.log(response)
          wx.stopPullDownRefresh()
          var teamimglist = [];
          if (response.data.data.sh_product_team_number) {
            if (response.data.data.sh_product_team_number > 0) {
              for (var i = 0; i < response.data.data.sh_product_team_number; i++) {
                teamimglist[i] = {}
                teamimglist[i].imgbg = 'https://img-oss.shihanbainian.com/upload_dev/images/e/8/8/e881261c91322d65250e81ec8c8c62b7.png';
                if (response.data.data.sh_customer[i] && response.data.data.sh_customer[i].sh_nick_name) {
                  teamimglist[i].sh_nick_name = response.data.data.sh_customer[i].sh_nick_name;
                  teamimglist[i].sh_headimgurl = response.data.data.sh_customer[i].sh_headimgurl;
                }
              }
            }
          } else {
            var length = response.data.data.sh_customer.length;
            if (length > 0) {
              for (var i = 0; i < length; i++) {
                teamimglist[i] = {}
                teamimglist[i].imgbg = 'https://img-oss.shihanbainian.com/upload_dev/images/e/8/8/e881261c91322d65250e81ec8c8c62b7.png';
                if (response.data.data.sh_customer[i] && response.data.data.sh_customer[i].sh_nick_name) {
                  teamimglist[i].sh_nick_name = response.data.data.sh_customer[i].sh_nick_name;
                  teamimglist[i].sh_headimgurl = response.data.data.sh_customer[i].sh_headimgurl;
                }
              }
            }
          }
          response.data.data.sh_create_at = response.data.data.sh_create_at.replace(/-/g, '/');
          that.setData({
            showLoading: false,
            teamimglist: teamimglist,
            groupdetail: response.data.data,
            teamid: response.data.data.sh_team_id,
            goodsid: response.data.data.sh_product_id,
          })
          that.goodsdetail();
          if (response.data.data.sh_end_at) {
            clearInterval(goodstimer);
            goodstimer = setInterval(function() {
              var newgoodstime = {}
              newgoodstime['sh_end_time'] = response.data.data.sh_end_at
              that.timeCalculation(newgoodstime)
            }, 50)
          }
        }
      }, function(error) {
        console.log(error);
      });
  },
  // 拼团时间计算
  timeCalculation: function(staretime) { //sh_create_at:"2017-08-28 16:23:26" 秒杀时间计算
    var that = this
    var time1 = new Date().getTime(), //取得当前毫秒数
      time2 = new Date(staretime.sh_end_time.replace(/-/g, '/')); //取得指定时间的总毫秒数 

    if (time2 - time1 > 0) { //正在进行中
      var micro_second = time2 - time1;

      var time = micro_second / 1000;
      // 小时位
      var hour = Math.floor(time / 3600);
      hour = hour <= 9 ? '0' + hour : hour;
      // 分钟位
      var minute = Math.floor(time % 3600 / 60);
      minute = minute <= 9 ? '0' + minute : minute;
      // 秒数
      var second = Math.floor(time % 3600 % 60);
      second = second <= 9 ? '0' + second : second;
      //毫秒
      var millisecond = Math.floor((micro_second % 1000) / 100);

      that.setData({
        changetime: {
          status: true,
          changeHour: hour,
          changeMinute: minute,
          changeSecond: second + '.' + millisecond
        }
      })
    } else {
      that.setData({
        changetime: {
          status: false
        }
      })
      clearInterval(goodstimer);
      that.groupdetail(that.data.orderno)
    }
  },
  // 商品详情
  goodsdetail: function() {
    var that = this
    shihan.sendRequest(config.goods_detail + that.data.goodsid + '.html', 'GET', {})
      .then(function(response) {
        if (response.data.code == 0) {
          wx.reportAnalytics('page_product_detail', {
            product_id: that.data.goodsid,
            product_name: response.data.data.sh_name
          })
          that.setData({
            goodsinfo: response.data.data
          })
        }
      }, function(error) {
        console.log(error);
      });
  },
  openshareimg: function() {
    var that = this;
    wx.showLoading({
      title: '绘制中',
      mask: true
    })
    that.setData({
      painting: {
        width: 750,
        height: 1126,
        clear: true,
        views: [
          {
            type: 'image',
            url: 'https://img-oss.shihanbainian.com/upload_dev/images/6/6/9/669cccc81ec823e50d356887eadf8790.jpg',
            top: 0,
            left: 0,
            width: 750,
            height: 1126
          },
          {
            type: 'image',
            url: that.data.goodsinfo.sh_galleries[0],
            top: 0,
            left: 0,
            width: 750,
            height: 750
          },
          {
            type: 'image',
            url: 'https://img-oss.shihanbainian.com/upload_dev/images/f/5/a/f5a276c8ebbca95583d0e682aa246c66.png',
            top: 0,
            left: 30,
            width: 130,
            height: 138
          },
          {
            type: 'image',
            url: that.data.goodsinfo.sh_headimgurl,
            top: 706,
            left: 30,
            width: 90,
            height: 90,
            borderRadius: 45
          },
          {
            type: 'image',
            url: 'https://img-oss.shihanbainian.com/upload_dev/images/c/2/a/c2ab344bb67143209b9f0b012b8307b7.png',
            top: 666,
            left: 0,
            width: 750,
            height: 136
          },
          {
            type: 'image',
            url: that.data.groupdetail.sh_share_data&&that.data.groupdetail.sh_share_data.sh_qrcode || 'https://img-oss.shihanbainian.com/shihan2/index/defaults.png',
            top: 790,
            left: 480,
            width: 240,
            height: 240
          },
          {
            type: 'image',
            url: 'https://img-oss.shihanbainian.com/upload_dev/images/f/b/0/fb0f60a5434ace69cf2316a817913b4d.png',
            top: 1050,
            left: 30,
            width: 100,
            height: 40
          },
          {
            type: 'text',
            content: that.data.groupdetail.sh_nick_name,
            fontSize: 32,
            color: '#444',
            textAlign: 'left',
            top: 750,
            left: 142
          },
          {
            type: 'text',
            content: that.data.groupdetail.sh_share_data.sh_title,
            fontSize: 32,
            color: '#444',
            textAlign: 'left',
            top: 825,
            left: 30,
            width: 410,
            lineHeight: 46,
            breakWord: true,
            MaxLineNumber: 2
          },
          {
            type: 'text',
            content: '快来拼团和我一起享受优惠~',
            fontSize: 28,
            color: '#999',
            textAlign: 'left',
            top: 930,
            left: 30
          },
          {
            type: 'text',
            line: 1,
            margin: 10,
            content: '￥' + that.data.goodsinfo.sh_show_price,
            fontSize: 36,
            color: '#cc363c',
            textAlign: 'left',
            top: 1050,
            left: 138,
            bolder: true
          },
          {
            type: 'text',
            content: '￥' + that.data.goodsinfo.sh_line_price,
            fontSize: 32,
            color: '#999',
            textAlign: 'left',
            top: 1056,
            left: 316,
            textDecoration: 'line-through'
          },
          {
            type: 'text',
            content: '扫描或长按二维码',
            fontSize: 28,
            color: '#666',
            textAlign: 'left',
            top: 1064,
            left: 486
          }
        ]
      }
    })
  },
  eventGetImage: function (event) {
    // console.log(event)
    const { tempFilePath, errMsg } = event.detail;
    if (errMsg === 'canvasdrawer:ok') {
      this.setData({
        shareImage: tempFilePath
      })
    }
    this.previewImage(this.data.shareImage);
  },
  previewImage: function (url) {
    var that = this, imgarr = [];
    imgarr.push(url)
    wx.hideLoading()
    wx.previewImage({
      urls: imgarr,
      success: function () {}
    })
  },
  getmygroup: function() {
    wx.navigateTo({
      url: '/pages/other/groupbuy/groupbuy'
    })
  },
  goonbuy: function() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  lookorder: function(e) {
    wx.redirectTo({
      url: '/pages/other/myorderdetail/myorderdetail?orderid=' + e.currentTarget.dataset.orderno,
    })
  },
  viewgoodsDetail: function(e) {
    wx.navigateTo({
      url: '/pages/goodsdetail/goodsdetail?goodsid=' + e.currentTarget.dataset.id
    })
  },
  moregroup: function() {
    this.animation1.translateY(-range1).step();
    this.setData({
      filterConflag: true,
      animationData1: this.animation1.export()
    })
  },
  closegroup: function() {
    this.animation1.translateY(range1).step();
    this.setData({
      filterConflag: false,
      animationData1: this.animation1.export()
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    clearInterval(goodstimer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(goodstimer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.groupdetail(this.data.orderno)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var that = this,
      shareurl;
    var customerId = wx.getStorageSync('customerId') || ''
    shareurl = '/pages/other/teamdetail/teamdetail?teamid=' + that.data.teamid + '&pid=' + customerId
    return {
      title: '【帮我拼一单】' + that.data.goodsinfo.sh_name,
      path: shareurl,
      imageUrl: that.data.goodsinfo.sh_galleries[0],
      success: function(res) {},
      fail: function(res) {
        // 转发失败
      }
    }
  }
})